#!/bin/sh
# Torberry build scripts.
# Works with spindle http://asbradbury.org/projects/spindle
# See LICENSE.spindle file for copyright and license details
# See README for building details

set -ex

. ./common

CURIMG=stage4-torberry.$IMGFORMAT

install_packages() {
  # we may want to break out DEBIAN_FRONTEND=noninteractive
  ssh_in_to_qemu /usr/sbin/chroot /mnt sh -l -ex - <<EOF
apt-get update
apt-get install -y --no-install-recommends tor iptables ntpdate netbase tor-arm
apt-get install -y isc-dhcp-server
apt-get install -y python-cherrypy3 python-jinja2 python-pam
update-rc.d networking disable
update-rc.d ifplugd disable
update-rc.d isc-dhcp-server disable 
update-rc.d tor disable
ln -s /bin/busybox /sbin/route
ln -s /bin/busybox /sbin/ifconfig
ln -s /bin/busybox /sbin/netstat
ln -s /bin/busybox /bin/vi
ln -s /bin/busybox /bin/wget
rm -rf /etc/motd
EOF
}


configure_sysctl() {
  onvm_chroot sh -l -e <<\EOF
cat << EOF1 > /etc/sysctl.conf
#
# /etc/sysctl.conf - Configuration file for setting system variables
# See /etc/sysctl.d/ for additonal system variables
# See sysctl.conf (5) for information.
#

net.ipv4.icmp_echo_ignore_all=1
net.ipv4.conf.eth0.accept_redirects=0
net.ipv4.conf.all.accept_redirects=0
net.ipv4.conf.eth0.send_redirects=0
net.ipv4.conf.all.send_redirects=0

#kernel.domainname = example.com

# Uncomment the following to stop low-level messages on console
kernel.printk = 3 4 1 3

##############################################################3
# Functions previously found in netbase
#

# Uncomment the next two lines to enable Spoof protection (reverse-path filter)
# Turn on Source Address Verification in all interfaces to
# prevent some spoofing attacks
#net.ipv4.conf.default.rp_filter=1
#net.ipv4.conf.all.rp_filter=1

# Uncomment the next line to enable TCP/IP SYN cookies
# See http://lwn.net/Articles/277146/
# Note: This may impact IPv6 TCP sessions too
#net.ipv4.tcp_syncookies=1

# Uncomment the next line to enable packet forwarding for IPv4
#net.ipv4.ip_forward=1

# Uncomment the next line to enable packet forwarding for IPv6
#  Enabling this option disables Stateless Address Autoconfiguration
#  based on Router Advertisements for this host
#net.ipv6.conf.all.forwarding=1


###################################################################
# Additional settings - these settings can improve the network
# security of the host and prevent against some network attacks
# including spoofing attacks and man in the middle attacks through
# redirection. Some network environments, however, require that these
# settings are disabled so review and enable them as needed.
#
# Do not accept ICMP redirects (prevent MITM attacks)
#net.ipv4.conf.all.accept_redirects = 0
#net.ipv6.conf.all.accept_redirects = 0
# _or_
# Accept ICMP redirects only for gateways listed in our default
# gateway list (enabled by default)
# net.ipv4.conf.all.secure_redirects = 1
#
# Do not send ICMP redirects (we are not a router)
#net.ipv4.conf.all.send_redirects = 0
#
# Do not accept IP source route packets (we are not a router)
#net.ipv4.conf.all.accept_source_route = 0
#net.ipv6.conf.all.accept_source_route = 0
#
# Log Martian Packets
#net.ipv4.conf.all.log_martians = 1
#

# rpi tweaks
vm.swappiness=1
vm.min_free_kbytes = 8192
EOF1
EOF
}

configure_torberryinit() {
  onvm_chroot sh -l -e <<\EOF
cat << EOF1 > /etc/torberry.sh
#!/bin/bash
# Torberry init script
#
if [ "\$L1" == "tty1" ]; then
clear
cat /etc/torberry-issue
. /lib/lsb/init-functions
iptables -F
iptables -t nat -F
trap "" 1 2 3 9 15
if [ -f /etc/firstrun ]; then
 echo "Torberry first start!"
 echo "We need to regenerate dropbear host keys. Be patient..."
 service dropbear stop
 rm /etc/dropbear/dropbear_dss_host_key
 rm /etc/dropbear/dropbear_rsa_host_key
 echo "Generating Dropbear RSA key..." 
 dropbearkey -t rsa -f /etc/dropbear/dropbear_rsa_host_key -s 1024
 echo "Generating Dropbear DSS key..." 
 dropbearkey -t dss -f /etc/dropbear/dropbear_dss_host_key -s 1024
 chmod 600 /etc/dropbear/dropbear_dss_host_key
 chmod 600 /etc/dropbear/dropbear_rsa_host_key
 service dropbear start
 rm /etc/firstrun
fi
if [ -f /etc/resizeflag ]; then
 echo "root partition resize requested."
 echo "it will take some time..."
 service ifplugd stop
 service dropbear stop
 resize2fs /dev/root
 rm /etc/resizeflag
 service ifplugd start
 service dropbear start
fi
echo "Torberry is starting..."
log_action_begin_msg "Mounting temp dirs..."
mount -t tmpfs -o size=6M,uid=101,gid=102 tmpfs /var/lib/tor
mount -t tmpfs -o size=6M,uid=101,gid=4 tmpfs /var/log/tor
log_action_end_msg 0
log_action_begin_msg "Waiting for a valid IP address..."
IP=\$(hostname -I)
while [ -z \$IP ]; do
 sleep 2
 IP=\$(hostname -I)
done
IP=\${IP%?}
log_progress_msg "[ \$IP ] "
log_action_end_msg 0
log_action_begin_msg "Setting current date..."
ntpdate hora.uv.es 2>&1 > /dev/null
log_action_end_msg 0
log_action_begin_msg "Setting iptables rules..."
NETWORK=\$(netstat -nr | tail -1 | awk '{print \$1 }')
NON_TOR=\$NETWORK"/24"
TOR_UID="debian-tor"
TRANS_PORT="9040"
INT_IF="eth0"
iptables -t nat -A OUTPUT -o lo -j RETURN
iptables -t nat -A OUTPUT -m owner --uid-owner \$TOR_UID -j RETURN
iptables -t nat -A OUTPUT -p udp --dport 53 -j REDIRECT --to-ports 53
for NET in \$NON_TOR; do
 iptables -t nat -A OUTPUT -d \$NET -j RETURN
 iptables -t nat -A PREROUTING -i \$INT_IF -d \$NET -j RETURN
done
iptables -t nat -A OUTPUT -p tcp --syn -j REDIRECT --to-ports \$TRANS_PORT
iptables -t nat -A PREROUTING -i \$INT_IF -p udp --dport 53 -j REDIRECT --to-ports 53
iptables -t nat -A PREROUTING -i \$INT_IF -p tcp --syn -j REDIRECT --to-ports \$TRANS_PORT
iptables -A OUTPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
for NET in \$NON_TOR 127.0.0.0/8; do
 iptables -A OUTPUT -d \$NET -j ACCEPT
done
iptables -A OUTPUT -m owner --uid-owner \$TOR_UID -j ACCEPT
iptables -A OUTPUT -j REJECT
iptables -A OUTPUT -p icmp -j REJECT
iptables -A INPUT -p icmp -j REJECT
log_action_end_msg 0
cp /etc/tor/torrc.orig /etc/tor/torrc
echo "TransPort "\$IP":9040" >> /etc/tor/torrc
echo "DNSPort "\$IP":53" >> /etc/tor/torrc
echo "SocksPort "\$IP":9050" >> /etc/tor/torrc
echo "nameserver 127.0.0.1" > /etc/resolv.conf
service tor start
/usr/lib/pymodules/python2.7/TorCtl/torberry-boot.py
while [ true ]; do
 sleep 1
done 
else
 return 0
fi

EOF1
cat << EOF2 > /etc/init.d/rcS
#!/bin/sh
#
# rcS
#
# Call all S??* scripts in /etc/rcS.d/ in numerical/alphabetical order
#

exec /etc/init.d/rc S > /dev/null 2>&1
EOF2
mkdir -p /root/goodies
wget http://torberry.googlecode.com/svn/trunk/extras/torberry-issue -O /etc/torberry-issue
wget http://torberry.googlecode.com/svn/trunk/extras/expandfs -O /root/goodies/expandfs
wget http://torberry.googlecode.com/svn/trunk/extras/torberry-boot.py -O /usr/lib/pymodules/python2.7/TorCtl/torberry-boot.py
rm /etc/torberry.sh
wget http://torberry.googlecode.com/svn/trunk/extras/torberry.sh -O /etc/torberry.sh
wget http://torberry.googlecode.com/svn/trunk/extras/torberry.conf -O /etc/torberry.conf
#wget http://cdn.bitcloud.es/torberry.sh -O /etc/torberry.sh
#wget http://cdn.bitcloud.es/torberry.conf -O /etc/torberry.conf
mkdir -p /root/HttpServer/templates
mkdir -p /root/HttpServer/templates/bootstrap/css
mkdir -p /root/HttpServer/templates/bootstrap/img
mkdir -p /root/HttpServer/templates/bootstrap/js
mkdir -p /root/HttpServer/templates/jquery
wget http://torberry.googlecode.com/svn/trunk/extras/web/web.config -O /root/web.config
wget http://torberry.googlecode.com/svn/trunk/extras/web/HttpServer/__init__.py -O /root/HttpServer/__init__.py
wget http://torberry.googlecode.com/svn/trunk/extras/web/HttpServer/torcon.py -O /root/HttpServer/torcon.py
wget http://torberry.googlecode.com/svn/trunk/extras/web/HttpServer/configBerry.py -O /root/HttpServer/configBerry.py
wget http://torberry.googlecode.com/svn/trunk/extras/web/HttpServer/templates/config.tpl -O /root/HttpServer/templates/config.tpl
wget http://torberry.googlecode.com/svn/trunk/extras/web/HttpServer/templates/orconfig.tpl -O /root/HttpServer/templates/orconfig.tpl
wget http://torberry.googlecode.com/svn/trunk/extras/web/HttpServer/templates/control.tpl -O /root/HttpServer/templates/control.tpl
wget http://torberry.googlecode.com/svn/trunk/extras/web/HttpServer/templates/footer.tpl -O /root/HttpServer/templates/footer.tpl
wget http://torberry.googlecode.com/svn/trunk/extras/web/HttpServer/templates/frame.tpl -O /root/HttpServer/templates/frame.tpl
wget http://torberry.googlecode.com/svn/trunk/extras/web/HttpServer/templates/header.tpl -O /root/HttpServer/templates/header.tpl
wget http://torberry.googlecode.com/svn/trunk/extras/web/HttpServer/templates/login.tpl -O /root/HttpServer/templates/login.tpl
wget http://torberry.googlecode.com/svn/trunk/extras/web/HttpServer/templates/reset.tpl -O /root/HttpServer/templates/reset.tpl
wget http://torberry.googlecode.com/svn/trunk/extras/web/HttpServer/templates/status.tpl -O /root/HttpServer/templates/status.tpl
wget http://torberry.googlecode.com/svn/trunk/extras/web/HttpServer/templates/style.css -O /root/HttpServer/templates/style.css
wget http://torberry.googlecode.com/svn/trunk/extras/web/HttpServer/templates/sysstatus.tpl -O /root/HttpServer/templates/sysstatus.tpl
wget http://torberry.googlecode.com/svn/trunk/extras/web/HttpServer/templates/uconfig.tpl -O /root/HttpServer/templates/uconfig.tpl
wget http://torberry.googlecode.com/svn/trunk/extras/web/HttpServer/templates/ufile.tpl -O /root/HttpServer/templates/ufile.tpl
wget http://torberry.googlecode.com/svn/trunk/extras/web/HttpServer/templates/jquery/jquery-1.10.1.min.js -O /root/HttpServer/templates/jquery/jquery-1.10.1.min.js
wget http://torberry.googlecode.com/svn/trunk/extras/web/HttpServer/templates/bootstrap/img/glyphicons-halflings.png -O /root/HttpServer/templates/bootstrap/img/glyphicons-halflings.png
wget http://torberry.googlecode.com/svn/trunk/extras/web/HttpServer/templates/bootstrap/img/glyphicons-halflings-white.png -O /root/HttpServer/templates/bootstrap/img/glyphicons-halflings-white.png
wget http://torberry.googlecode.com/svn/trunk/extras/web/HttpServer/templates/bootstrap/css/bootstrap-responsive.css -O /root/HttpServer/templates/bootstrap/css/bootstrap-responsive.css
wget http://torberry.googlecode.com/svn/trunk/extras/web/HttpServer/templates/bootstrap/css/bootstrap.css -O /root/HttpServer/templates/bootstrap/css/bootstrap.css
wget http://torberry.googlecode.com/svn/trunk/extras/web/HttpServer/templates/bootstrap/js/bootstrap.js -O /root/HttpServer/templates/bootstrap/js/bootstrap.js
wget http://torberry.googlecode.com/svn/trunk/extras/web/HttpServer/templates/bootstrap/js/bootstrap.file-input.js -O /root/HttpServer/templates/bootstrap/js/bootstrap.file-input.js
wget http://torberry.googlecode.com/svn/trunk/extras/web/HttpServer/templates/bootstrap/js/bootstrap.min.js -O /root/HttpServer/templates/bootstrap/js/bootstrap.min.js

chmod +x /root/goodies/expandfs
chmod +x /usr/lib/pymodules/python2.7/TorCtl/torberry-boot.py
touch /etc/firstrun
EOF
}

configure_tor() {
  onvm_chroot sh -l -e <<\EOF
cat << EOF1 > /etc/tor/torrc.orig
SocksPort 9050
Log notice file /var/log/tor/notices.log
DisableDebuggerAttachment 0
VirtualAddrNetwork 10.192.0.0/10
AutomapHostsOnResolve 1
TransPort 9040
DNSPort 53
EOF1
EOF
}


cd $WORKDIR
dotask branch_image ../$OUTDIR/stage3.$IMGFORMAT $CURIMG
dotask run_qemu $CURIMG
dotask mount_apt_cache
dotask disable_starting_services

dotask install_packages
dotask configure_sysctl
dotask configure_tor
dotask configure_torberryinit

dotask save_space_using_hardlink
dotask allow_starting_services
dotask update_issue
#dotask fingerprint_debian
dotask shutdown_qemu
dotask finish_image
